package cloud.mbase.business;

import cloud.mbase.business.interf.UserBusinessInterface;
import cloud.mbase.dao.ResourceDao;
import cloud.mbase.dao.RoleDao;
import cloud.mbase.dao.UserDao;
import cloud.mbase.entity.datavo.Mrole;
import cloud.mbase.entity.datavo.Muser;
import cloud.mbase.entity.datavo.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserBusiness implements UserBusinessInterface {
    @Autowired
    private ResourceDao resourceDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Resource> findAllResource() {
        return resourceDao.findAll();
    }

    @Override
    public Resource getResourceById(Integer id) {
        return resourceDao.findOne(id);
    }

    @Override
    public Resource saveResource(Resource resource) {
        return resourceDao.save(resource);
    }

    @Override
    public void deleteResource(Integer id) {
        resourceDao.delete(id);
    }

    @Override
    public Muser saveUser(Muser user) {
        return userDao.save(user);
    }

    @Override
    public Muser findByUserName(String userName) {
        return userDao.findByUserName(userName);
    }

    @Override
    public boolean setUserAuth(Integer userId, String roleName) {
        Muser muser = userDao.findOne(userId);
        List<Mrole> roles = roleDao.findByRole(roleName);
        if (muser != null && roles != null && roles.size() > 0) {
            muser.addMrole(roles);
            userDao.save(muser);
            return true;
        }
        return false;
    }
}
